//
//  AppleScriptInterface.m
//  Pennyworth Punch Clock
//
//  Created by Chris Karr on 7/24/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "AppleScriptInterface.h"
#import "AppDelegate.h"
#import <Carbon/Carbon.h>

@implementation AppleScriptInterface

- (void) awakeFromNib
{
	cache = [[NSMutableDictionary alloc] init];
	labelTimers = [[NSMutableDictionary alloc] init];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processUpdate:) name:PREDICTION_FETCHED object:nil];
	
	[[NSTimer scheduledTimerWithTimeInterval:3600 target:self selector:@selector(clearCaches:) userInfo:nil repeats:YES] retain];
}

- (void) clearCaches:(NSTimer *) theTimer
{
	[cache removeAllObjects];
}

- (void) processUpdate:(NSNotification *) note
{
	NSDictionary * userInfo = [note userInfo];
	
	BOOL update = NO;
	
	NSString * key = [userInfo valueForKey:KEY];
	NSObject * value = [userInfo valueForKey:PREDICTION];
	
	if (key == nil || value == nil)
		return;
	
	if (![value isEqual:[cache valueForKey:key]])
	{
		[cache setValue:value forKey:key];
		update = YES;
	}
	
	if (update)
	{
		NSTimer * labelTimer = [labelTimers valueForKey:key];
		
		if (labelTimer != nil)
			[labelTimer invalidate];
		
		labelTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(fire:) userInfo:
					  [NSDictionary dictionaryWithObject:value forKey:key] repeats:NO];
		
		[labelTimers setValue:labelTimer forKey:key];
	}
}

- (void) fire:(NSTimer *) theTimer
{	
	NSString * scriptPath = [NSString stringWithFormat:@"%@/AppleScript", [((AppDelegate *) [NSApp delegate]) applicationSupportFolder]];

	// NSLog (@"dir = %@", scriptPath);

	NSDictionary * userInfo = [theTimer userInfo];
	
	NSString * key = [[userInfo allKeys] lastObject];
	NSObject * value = [userInfo valueForKey:key];
	
	NSFileManager * fm = [NSFileManager defaultManager];
	BOOL isDir = NO;
	
	if ([fm fileExistsAtPath:scriptPath isDirectory:&isDir] && isDir)
	{
		NSArray * files = [[fm directoryContentsAtPath:scriptPath] sortedArrayUsingSelector:@selector(compare:)];
		
		for (NSString * file in files)
		{
			if ([file hasSuffix:@".scpt"])
			{
				NSDictionary * errors = [NSDictionary dictionary];
				NSURL * scriptUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", scriptPath, file]];
				
				NSAppleScript * scpt = [[NSAppleScript alloc] initWithContentsOfURL:scriptUrl error:nil];
				
				if (scpt != nil)
				{
					NSAppleEventDescriptor * type = [NSAppleEventDescriptor descriptorWithString:key];
					NSAppleEventDescriptor * prediction = [NSAppleEventDescriptor descriptorWithString:[value description]];
					
					NSAppleEventDescriptor * parameters = [NSAppleEventDescriptor listDescriptor];
					[parameters insertDescriptor:type atIndex:1];
					[parameters insertDescriptor:prediction atIndex:2];
					
					ProcessSerialNumber psn = { 0, kCurrentProcess };
					NSAppleEventDescriptor * target = [NSAppleEventDescriptor descriptorWithDescriptorType:typeProcessSerialNumber
																									 bytes:&psn
																									length:sizeof(ProcessSerialNumber)];
					
					NSAppleEventDescriptor *handler = [NSAppleEventDescriptor descriptorWithString:@"update"];
					
					NSAppleEventDescriptor *event = [NSAppleEventDescriptor appleEventWithEventClass:kASAppleScriptSuite
																							 eventID:kASSubroutineEvent
																					targetDescriptor:target
																							returnID:kAutoGenerateReturnID
																					   transactionID:kAnyTransactionID];
					
					[event setParamDescriptor:handler forKeyword:keyASSubroutineName];
					[event setParamDescriptor:parameters forKeyword:keyDirectObject];
					
					[scpt executeAppleEvent:event error:&errors];
					[scpt release];
				}
			}
		}
	}
	else
		[fm createDirectoryAtPath:scriptPath withIntermediateDirectories:YES attributes:nil error:nil];
}


@end
